package com.tangguangdi.shield.server.config;

import com.tangguangdi.base.common.variable.RegisterVar;
import com.tangguangdi.base.core.register.RegisterServer;
import com.tangguangdi.shield.server.permission.PermissionCache;
import com.tangguangdi.shield.server.properties.ShieldProperties;
import com.tangguangdi.shield.server.receiver.MessageReceiver;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

@Configuration
public class GatewayAutoConfiguration {

    @Bean
    @ConfigurationProperties(prefix = "max.shield")
    public ShieldProperties shieldProperties() {
        return new ShieldProperties();
    }

    @Bean
    public PermissionCache permissionCache(RegisterServer registerServer) {
        return new PermissionCache(registerServer);
    }

    @Bean
    public MessageReceiver receiver() {
        return new MessageReceiver();
    }

    @Bean
    MessageListenerAdapter listenerAdapter(MessageReceiver receiver) {
        return new MessageListenerAdapter(receiver, "onMessage");
    }

    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                                   MessageListenerAdapter listenerAdapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(listenerAdapter, new PatternTopic(RegisterVar.appUpdateTopic));
        return container;
    }
}
